<template>
  <div>
    <el-upload
      list-type="picture-card"
      action="#"
      :file-list="fileList"
      :class="{disable: fileList.length>0}"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="upload"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress
      v-if="isShowPercent"
      :text-inside="true"
      :stroke-width="20"
      :percentage="percent"
      style="width:146px"
    />
    <el-dialog title="预览" :visible="isShowDialog" @close="isShowDialog=false">
      <el-row type="flex" justify="center">
        <img :src="previewURL" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKID87qJVQ5UbRzoPkoc9PO6XhaFdka8QQ9b',
  SecretKey: 'EBsKWR5SZQ0JL6crpWw5wWprb4GCrEJ7'
})
export default {
  data() {
    return {
      fileList: [],
      isShowDialog: false,
      previewURL: '',
      percent: 0,
      isShowPercent: false
    }
  },
  methods: {
    onPreview(file) {
    //   console.log(34, file)
      this.isShowDialog = true
      this.previewURL = file.url
    },
    onRemove(file, newFileList) {
      this.fileList = newFileList
    },
    onChange(file, newFileList) {
      this.fileList = newFileList
    },
    upload(params) {
      this.isShowPercent = true
      //   console.log(54, params)
      cos.putObject({
        Bucket: 'hr-1308523004', /* 存储桶名字 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 文件名 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percent = Math.round(progressData.percent * 100)
        }
      }, (err, data) => {
        console.log(err || data)
        this.fileList[0].url = 'http://' + data.Location
        this.fileList[0].status = 'success'
        setTimeout(() => {
          this.isShowPercent = false
        }, 800)
      })
    },
    beforeUpload(file) {
      // 校验大小
      const maxSize = 2 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.warning('文件大小不能超过 2M')
        return false
      }
      // 校验格式
      const whiteList = ['image/png', 'image/jpeg']
      if (!whiteList.includes(file.type)) {
        this.$message.warning('暂时只支持 png和jpeg 格式文件上传')
        return false
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.disable {
    ::v-deep .el-upload--picture-card {
        display: none;
    }
}
</style>

<style lang='scss'>
img {
  object-fit: cover;
}
</style>
